package com.flow.asyncflow.core.utils.ocr;

import com.baidu.aip.ocr.AipOcr;
import lombok.SneakyThrows;
import org.json.JSONObject;

import java.util.Base64;
import java.util.HashMap;

public class BaiDuOcrUtil {
    public static volatile AipOcr aipOcr = null;
    //设置APPID/AK/SK
    public static final String APP_ID = "31771071";
    public static final String API_KEY = "xxxxxxxx";
    public static final String SECRET_KEY = "xxxxxxxx";
    public static final int CONNECTION_TIME_OUT = 2000;//建立连接的超时时间（单位：毫秒）
    public static final int SOCKET_TIME_OUT = 6000;//通过打开的连接传输数据的超时时间（单位：毫秒）

    private BaiDuOcrUtil() {
    }

    public static AipOcr getAipOcr() {
        if (aipOcr == null) {
            synchronized (BaiDuOcrUtil.class) {
                if (aipOcr == null) {
                    aipOcr = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
                    // 可选：设置网络连接参数
                    aipOcr.setConnectionTimeoutInMillis(CONNECTION_TIME_OUT);
                    aipOcr.setSocketTimeoutInMillis(SOCKET_TIME_OUT);
                    //setHttpProxy 设置http代理服务器
                    //setSocketProxy 设置socket代理服务器 （http和socket类型代理服务器只能二选一）
                }
            }
        }
        return aipOcr;
    }







    /**
     * 自定义模OCR
     * @param imageByte 字节流
     * @param templateSign 模板Id
     * @return 识别结果
     */
    public static JSONObject customOCR(byte[] imageByte, String templateSign) {
        // 初始化一个AipOcr
        AipOcr client = getAipOcr();
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>();
        options.put("templateSign", templateSign);
        //options.put("access_token", AipOcrSingleton.getAccessToken());
        JSONObject jsonObject = client.custom(imageByte, options);
        System.out.println(jsonObject.toString());
        return jsonObject;

    }




}
